package com.walker.component.page.resolve.query;

import java.util.ArrayList;
import java.util.List;

import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.walker.component.page.resolve.query.annotation.Required;

/**
 * 列表集合查询
 * 
 * @author 三丰
 * 
 */
public class ListQueryer implements Queryer {
	private String cssQuery;
	private Queryer mapper;
	private int index = -1;

	@Required
	public void setCssQuery(String cssExprStr) {
		this.cssQuery = cssExprStr;
	}

	public void setIndex(int index) {
		this.index = index;
	}

	@Required
	public void setMapper(Queryer mapper) {
		this.mapper = mapper;
	}

	public ListQueryer() {
	}

	public ListQueryer(String fromExpr, Queryer mapper) {
		setCssQuery(fromExpr);
		setMapper(mapper);
	}

	@SuppressWarnings("rawtypes")
	public Object query(Document document) {
		Elements eles = document.select(this.cssQuery);
		List results = new ArrayList();
		if ((this.index > -1) && (this.index < eles.size())) {
			Object r = this.mapper.query(eles.get(this.index));
			return r;
		}
		for (int i = 0; i < eles.size(); ++i) {
			Object r = this.mapper.query(eles.get(i));
			results.add(r);
		}
		return results;
	}

	@SuppressWarnings("rawtypes")
	public Object query(Element element) {
		Elements eles = element.select(this.cssQuery);
		List results = new ArrayList();
		if ((this.index > -1) && (this.index < eles.size())) {
			Object r = this.mapper.query(eles.get(this.index));
			return r;
		}
		for (int i = 0; i < eles.size(); ++i) {
			Object r = this.mapper.query(eles.get(i));
			results.add(r);
		}
		return results;
	}
}
